package com.hmkj.web.controller.index;

import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.constant.PhoneCodeKey;
import com.hmkj.core.constant.SessionId;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.user.UserModel;
import com.hmkj.core.po.operate.Agent;
import com.hmkj.core.po.user.User;
import com.hmkj.core.po.user.UserFreeze;
import com.hmkj.core.service.operate.AgentService;
import com.hmkj.core.service.user.UserFreezeService;
import com.hmkj.core.service.user.UserService;
import com.hmkj.web.controller.GenericController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 用户登录
 * @author Administrator
 */
@Api(description = "用户登录相关")
@Slf4j
@RestController
@RequestMapping(GenericController.BASE_API_URL)
public class  LoginController extends GenericController<Integer, User> {


    @Resource
    private UserService userService;
    @Resource
    private AgentService agentService;
    @Resource
    private UserFreezeService userFreezeService;

    @ApiOperation(value = "用户登录", notes = "用户登录,rsa公钥:<br/>-----BEGIN PUBLIC KEY-----<br/>" +
            "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChMRzbRbNqutRD8DEa52AJP+ee<br/>" +
            "nq+hiOKMjAHZtyb50HCypTqyJoJBoZ8doLBoH84D/XUsLEafqMFwicl4JOmNc/Ui<br/>" +
            "x+Glq6lsVpvTo7foIpx6+yuujp8yoLIFixPwq3WHZAHUIeCmJx8JoRjDeNJVMrnP<br/>" +
            "0HrHIZRM2ADEN8mE7QIDAQAB<br/>" +
            "-----END PUBLIC KEY-----")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultEntity login(@ApiParam("手机号") @RequestParam String userName,
                              @ApiParam("密码(rsa加密再base64加密)") @RequestParam String password,
                              HttpServletRequest request) {
        log.info("web用户登录");
        UserModel userModel = new UserModel(u -> {
            u.setPassword(password);
            u.setMobile(userName);
            u.setLastLoginDate(new Date());
            u.setLastLoginIp(getRequestIp(request));
        });

        userModel.checkLogin();
        // 校验用户名是否存在
        final User user = userService.selectOne(new User(u -> u.setMobile(userModel.getMobile())));
        if (user == null || user.getId() == null) {
            throw new BussinessException("用户名不存在");
        }
        //校验用户登录是否冻结
        UserFreeze userFreeze = userFreezeService.selectOne(new UserFreeze(f ->{
            f.setDelFlag(UserFreeze.DELFLAG.NORMAL.code);
            f.setUserId(user.getId());
        }));
        if(null == userFreeze || UserFreeze.STATUS.T1.code != userFreeze.getFreezingLogin()){
            throw new BussinessException("您的账户登录功能已被冻结，请联系客服处理");
        }
        // 校验用户名密码
        if (!UserModel.encodePwd(userModel.decryptPwd()).equals(user.getPassword())) {
            throw new BussinessException("密码错误,请重试");
        }
        userService.doLogin(userModel, request);
        return ok(m -> m.put("id", user.getId()));
    }

    @ApiOperation(value = "短信登录", notes = "短信登录")
    @RequestMapping(value = "/msgLogin", method = RequestMethod.POST)
    public ResultEntity msgLogin(@ApiParam("手机号") @RequestParam String userName,
                                 @ApiParam("短信") @RequestParam String code,
                                 HttpServletRequest request) {
        log.info("短信登录");
        checkUserPhoneCode(userName, code, PhoneCodeKey.MSG_LOGIN);
        UserModel userModel = new UserModel(u -> {
            u.setMobile(userName);
            u.setLastLoginDate(new Date());
            u.setLastLoginIp(getRequestIp(request));
        });
        // 校验用户名是否存在
        final User user = userService.selectOne(new User(u -> u.setMobile(userModel.getMobile())));
        if (user == null || user.getId() == null) {
            throw new BussinessException("用户名不存在");
        }

        userService.doLogin(userModel, request);
        return ok(m -> m.put("id", user.getId()));
    }

    @ApiOperation(value = "短信登录-发送短信", notes = "短信登录-发送短信")
    @RequestMapping(value = "msgLogin/send", method = RequestMethod.POST)
    public ResultEntity msgLoginSend(@ApiParam("手机号") @RequestParam final String userName,
                                     @ApiParam("图片验证码") @RequestParam(required = false) String captcha) throws Exception {
        if (StringUtils.isNotBlank(captcha) && !checkCaptcha(captcha)) {
            throw new BussinessException("图片验证码错误");
        }
        int i = userService.selectCount(new User(u -> u.setMobile(userName)));
        if (i != 1) {
            throw new BussinessException("未注册用户");
        }
        String domain = getDomain();
        Agent agent = agentService.selectAgentByDomain(domain);
        if (agent != null) {
            sendSmsCode(PhoneCodeKey.MSG_LOGIN, userName,agent.getId());
        } else {
            throw new BussinessException("代理商不存在");
        }

        return ok();
    }

    @ApiOperation(value = "用户登出", notes = "用户登出")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public ResultEntity logout(HttpServletRequest request) {
        log.info("web用户登出");
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(getLoginUser().getId());
            u.setHid("");
        }));
        String hid = request.getParameter(SessionId.COOKIE_SESSIONID);
        redisService.del("SESSION:" + hid);
        // 登录动作
        return ok();
    }

//    @ApiOperation(value = "找回密码1", notes = "找回密码1")
//    @RequestMapping(value = "codetopwd", method = RequestMethod.POST)
//    public ResultEntity getCodeToPwd(@ApiParam("手机号") @RequestParam String mobile,
//                                     @ApiParam("图片验证码") @RequestParam String captcha) throws Exception {
//        log.info("忘记密码获取手机验证码");
//        if (!checkCaptcha(captcha)) {
//            throw new BussinessException("验证码错误");
//        }
//        final Integer i = userService.selectCount(new User(u -> u.setMobile(mobile)));
//        if (i != 1) {
//            throw new BussinessException("当前用户不存在");
//        }
//        return ok();
//    }

    @ApiOperation(value = "找回密码1", notes = "找回密码1")
    @RequestMapping(value = "codetopwd", method = RequestMethod.POST)
    public ResultEntity getCodeToPwd(@ApiParam("手机号") @RequestParam String mobile,
                                     @ApiParam("手机验证码") @RequestParam String captcha) throws Exception {
        log.info("忘记密码校验手机验证码");
        final Integer i = userService.selectCount(new User(u -> u.setMobile(mobile)));
        if (i != 1) throw new BussinessException("当前用户不存在");
        checkUserPhoneCode(mobile, captcha, PhoneCodeKey.RESET_PWD);
        return ok();
    }

    @ApiOperation(value = "找回密码2", notes = "找回密码2")
    @RequestMapping(value = "editPwd", method = RequestMethod.POST)
    public ResultEntity editPwd(@ApiParam("手机号") @RequestParam String mobile,
                                @ApiParam("验证码") @RequestParam String code,
                                @ApiParam("密码") @RequestParam String password) throws Exception {
        log.info("忘记密码修改密码");
        checkUserPhoneCode(mobile, code, PhoneCodeKey.RESET_PWD);
        User user = userService.selectOne(new User(u -> {
            u.setMobile(mobile);
            u.setDelFlag(User.DELFLAG.NORMAL.code);
        }));
        if (null == user) {
            throw new BussinessException("该手机暂未注册用户");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(user.getId());
            u.setPassword(UserModel.staticEncodePwd(UserModel.staticDecryptPwd(password)));
        }));
        return ok();
    }

    @ApiOperation(value = "找回密码-发送短信", notes = "找回密码-发送短信")
    @RequestMapping(value = "sendCode", method = RequestMethod.POST)
    public ResultEntity sendCode(@ApiParam("手机号") @RequestParam String mobile) throws Exception {
        log.info("忘记密码修改密码");
        User user = userService.selectOne(new User(u -> {
            u.setMobile(mobile);
            u.setDelFlag(User.DELFLAG.NORMAL.code);
        }));
        if (null == user) {
            throw new BussinessException("该手机暂未注册用户");
        }
        String domain = getDomain();
        Agent agent = agentService.selectAgentByDomain(domain);
        if (agent != null) {
            sendSmsCode(PhoneCodeKey.RESET_PWD, mobile,agent.getId());
        } else {
            throw new BussinessException("代理商不存在");
        }
        return ok();
    }

}
